<?php
class Core_Controller_Autoloader {
	
	/**
	 * loadFile()
	 * load file 
	 * 
	 * @param $className: class to load
	 */
	public function loadFile($className){
		$filePath = $this->createFilePath($className);
		$this->fileLoad($filePath);
		//$this->classLoad($className);
	}
	
	public function classLoad($className){
		try {
			if(class_exists($className)){
				$class = new $className;
			}
			else {
				throw new Exception("Can't load class '$className'.");
			}
		}
		catch(Exception $e){
			echo $e->getMessage();
		}
	}
	
	/**
	 * fileLoad()
	 * load file to path
	 * 
	 * @param path to file $filePath
	 * @throws Exception
	 */
	public function fileLoad($filePath){
		try{
			if(file_exists($filePath)){
				require_once '$filePath';
			}
			else {
				throw new Exception("Filepath '<Strong>$filePath</strong> not found!");
			}
		}
		catch(Exception $e){
			echo $e->getMessage();
		}
	}
	
	/** 
	 * createFilePath()
	 * create file path
	 * 
	 * @param class name $className
	 * @return string filePath
	 */
	public function createFilePath($className){
		
		list($filename, $suffix) = preg_split('/_/', strrev($className), 2);
		$filename = strtolower(strrev($filename));
		$suffix = strrev($suffix);
		list($applicationTier, $functionality) = preg_split('/_/', strrev($suffix), 2);
		$functionality = strtolower(strrev($functionality));
		$applicationTier = strtolower(strrev($applicationTier));	
		
		$tierFolder = $this->getTierFolder($applicationTier);
		
		$filePath = basename(SERVER_ROOT) . "/" . basename($functionality) . "/" . basename($applicationTier) . "/" . $filename . ".php";
		
		echo $filePath;

		return $filePath;
	}
	
	public function getTierFolder($applicationTier){
		
		try {
			switch($applicationTier){
				case 'model':
					$folder = "model";
					break;
				case 'controller':
					$folder = "controller";
					break;
				case 'data':
					$folder = "data";
					break;
				case 'library':
					$folder = "libraries";
					break;
				case 'driver':
					$folder = "libraries/driver";
					break;
				default:
					throw new Exception("Invalid application tier: '$applicationTier'.");
			}
			return $folder;
		}
		catch(Exception $e){
			echo $e->getMessage();
		}
		
	}
	
}